<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Models;

use Sun\Sun;
use Sun\Html;
class Edition implements \Sun\IModel {
    public $db;
    public function __construct() {
        $this->db = new DB();
    }

    //////////////////////////////////////////////////////////////
    /////////////////////////FIELD////////////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddField($data) {
        try {
            $query = "INSERT INTO field(name, type_id)
                VALUES('{$data['name']}', '{$data['type_id']}')";
            $this->db->SafeExec($query);
        } catch (\Exception $e) {
            throw new \Sun\Exception("Имя не униально", 2);
        }
    }

    public function AltField($data) {
        try {
            $query = "UPDATE field SET name = '{$data['name']}'
                WHERE field_id = '{$data['field_id']}'";
            $this->db->SafeExec($query);
        } catch (\Exception $e) {
            throw new \Sun\Exception("Имя не униально", 2);
        }
    }

    public function DelField($data) {
        $query = "DELETE FROM field WHERE field_id = '{$data['field_id']}'";
        $this->db->SafeExec($query);
    }

    public function Dictionary($field_id) {
        $query = "SELECT value FROM dictionary WHERE field_id = '{.$field_id}'";
        return $this->db->SafeQuery($query);
    }


    //////////////////////////////////////////////////////////////
    /////////////////////////EDITIONTYPE//////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddEditionType($name, array $fields) {
        $this->db->beginTransaction();
        $query = "INSERT INTO edit_type(name) VALUES('{$name}')";
        $this->db->SafeExec($query);
        $type_id = $this->db->lastInsertId("edit_type_id");
        $query = "INSERT INTO type_field_rel(type_id, field_id) VALUES";
        for ($i = 0; $i < count($fields); ++$i) {
            $query .= "\n({$type_id}, {$fields[$i]})";
            if ($i < count($fields) - 1) $query.= ",";
        }
        $this->db->SafeExec($query);
        $this->db->commit();
    }

    public function AltEditionType($type_id, $name, array $fields) {
        $this->db->beginTransaction();
        $query = "UPDATE edit_type SET name = '{$name}' WHERE type_id = '{$type_id}'";
        $this->db->SafeExec($query);

        $query = "DELETE FROM type_field_rel WHERE type_id = '{$type_id}'";
        $this->db->SafeExec($query);
        $query = "INSERT INTO type_field_rel(type_id, field_id) VALUES";
        for ($i = 0; $i < count($fields); ++$i) {
            $query .= "\n({$type_id}, {$fields[$i]})";
            if ($i < count($fields) - 1) $query.= ",";
        }
        $this->db->SafeExec($query);
        $this->db->commit();
    }

    public function DelEditionType($type_id) {
        try {
            $this->db->beginTransaction();

            $query = "DELETE FROM type_field_rel WHERE type_id = '{$type_id}'";
            $this->db->SafeExec($query);
            $query = "DELETE FROM edit_type WHERE type_id = '{$type_id}'";
            $this->db->SafeExec($query);

            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollBack ();
            throw new \Sun\Exception('', 1);
        }
    }


    //////////////////////////////////////////////////////////////
    ///////////////////////////EDITIONS///////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddEdition($type, $fid, $fval, $file) {
        $this->db->beginTransaction();
        try {
            $query = "INSERT INTO edition(type_id)
                VALUES('{$type}')";
            $this->db->SafeExec($query);
            $edit = $this->db->lastInsertId("edit_id");

            for ($i = 0; $i < count($fid); ++$i) {
                if (empty($fval[$i])) continue;

                $query = "SELECT sense FROM field_type, field
                    WHERE field_id = '{$fid[$i]}' AND field.type_id = field_type.type_id";
                $sens = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
                $sens = $sens[0];

                $val = $this->db->quote($fval[$i]);
                $query = "SELECT rec_id FROM dictionary
                    WHERE field_id = '{$fid[$i]}' AND value = {$val}";
                $rec = $this->db->SafeQuery($query);
                if ($rec->rowCount() == 0) {
                    if ($sens != "STR" && empty($file[$i])) continue;

                    $query = "INSERT INTO dictionary(field_id, value) VALUES('{$fid[$i]}', {$val})";
                    $this->db->SafeExec($query);
                    $rec = $this->db->lastInsertId("dict_id");

                    if ($sens != "STR") {
                        $query = "SELECT path, name, uniname FROM file WHERE file_id = '{$file[$i]}'";
                        $res = $this->db->SafeQuery($query)->fetch(DB::FETCH_ASSOC);

                        $file_path = "pub/data/files/".$res['uniname'];
                        if (!copy($res['path'], $file_path))
                            throw new \Sun\Exception("Error copy file ".$res['path'], 400);

                        $query = "INSERT INTO dict_data(rec_id, path, name)
                            VALUES('{$rec}', '{$file_path}', '{$res['name']}')";
                        $this->db->SafeExec($query);
                    }
                } else {
                    $rec = $rec->fetch(DB::FETCH_NUM);
                    $rec = $rec[0];
                }
                $query = "INSERT INTO dict_rel(rec_id, edit_id) VALUES('{$rec}', '{$edit}')";
                $this->db->SafeExec($query);
            }
            $this->db->Commit();
            return $edit;
        } catch (\Sun\Exception $e) {
            $this->db->Rollback();
            throw $e;
        }
    }

    public function AltEdition($id, $type, $fid, $fval, $file) {
        $this->db->beginTransaction();
        $change = false;
        try {
            $query = "UPDATE edition SET type_id = '{$type}' WHERE edit_id = '{$id}'";
            $this->db->SafeExec($query);

            $query = "DELETE FROM dict_rel WHERE edit_id = '{$id}'";
            $this->db->SafeExec($query);

            for ($i = 0; $i < count($fid); ++$i) {
                if (empty($fval[$i])) continue;

                $query = "SELECT sense FROM field_type, field
                    WHERE field_id = '{$fid[$i]}' AND field.type_id = field_type.type_id";
                $sens = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
                $sens = $sens[0];

                $val = $this->db->quote($fval[$i]);
                $query = "SELECT rec_id FROM dictionary
                    WHERE field_id = '{$fid[$i]}' AND value = {$val}";
                $rec = $this->db->SafeQuery($query);
                if ($rec->rowCount() == 0) {
                    if ($sens != "STR" && empty($file[$i])) continue;

                    $query = "INSERT INTO dictionary(field_id, value) VALUES('{$fid[$i]}', {$val})";
                    $this->db->SafeQuery($query);
                    $rec = $this->db->lastInsertId("dict_id");

                    if ($sens != "STR") {
                        $query = "SELECT path, name, uniname FROM file WHERE file_id = '{$file[$i]}'";
                        $res = $this->db->SafeQuery($query)->fetch(DB::FETCH_ASSOC);

                        $file_path = "pub/data/files/".$res['uniname'];
                        if (!copy($res['path'], $file_path))
                            throw new \Sun\Exception("Error copy file ".$res['path'], 400);

                        $query = "INSERT INTO dict_data(rec_id, path, name)
                            VALUES('{$rec}', '{$file_path}', '{$res['name']}')";
                        $this->db->SafeQuery($query);
                    }
                } else {
                    $rec = $rec->fetch(DB::FETCH_NUM);
                    $rec = $rec[0];
                }
                $query = "INSERT INTO dict_rel(rec_id, edit_id) VALUES('{$rec}', '{$id}')";
                $this->db->SafeQuery($query);
                $change = true;
            }
            if (!$change)
                throw new \Sun\Exception ("Edit mast include at least one field", 402);
            else $this->db->commit();
        } catch (\Sun\Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    public function DelEdition($id) {
        $this->db->beginTransaction();
        try {
            $query = "DELETE FROM dict_rel WHERE edit_id = '{$id}'";
            $this->db->SafeExec($query);

            $query = "DELETE FROM edition WHERE edit_id = '{$id}'";
            $this->db->SafeExec($query);
        } catch (\Sun\Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
        $this->db->commit();
    }


    //////////////////////////////////////////////////////////////
    ///////////////////////////INVENTORY//////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddItem($edit_id, $count, $date) {
        $item_id = array();
        for ($i = 0; $i < $count; ++$i) {
            $query = "INSERT INTO inventory(edit_id, stat_id, entry_date)
                VALUES ({$edit_id}, 1, {$this->db->quote($date)})";
            $this->db->SafeExec($query);
            $item_id[] = $this->db->lastInsertId("inventory_id");
        }
        return $item_id;
    }


    //////////////////////////////////////////////////////////////
    /////////////////////////SEARCH///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function CreateSearchReq($type, $fields, $values, $ops, $sort) {

        $search = "WITH search as ((SELECT DISTINCT edit_id FROM catalog";
        if ((int)$type > -1)
            $search .= " WHERE edit_type = '{$type}') ";
        else $search .= ")";
        $cond = "";
        for ($i = 0; $i < count($fields); ++$i) {
            if (!empty($values[$i])) {

            $val = preg_replace('#\A\s+|\s+\z#', '', $values[$i]);
            $val = preg_replace(
                array("#[\|\(\)\:&\s]+#"),
                array("&"), $val);

                $field = $fields[$i] > -1 ? "field_id = {$fields[$i]} AND " : "";
                if ($ops[$i] == "OR") {
                    $cond .= empty($cond) ? " INTERSECT (" : ") \nUNION ";
                    if (empty($field)) $cond .= "(".$this->FTSQuery($val);
                    else $cond .= "\n(SELECT edit_id FROM catalog
                        WHERE ({$field} to_tsvector('russian', value)
                            @@ to_tsquery('russian', {$this->db->quote($val)}))";
                } else if ($ops[$i] == "AND") {
                    $cond .= empty($cond) ? " INTERSECT ((" : "\nINTERSECT";
                    if (empty($field)) $cond .= $this->FTSQuery($val);
                    else $cond .= "\nSELECT edit_id FROM catalog
                        WHERE ({$field} to_tsvector('russian', value)
                            @@ to_tsquery('russian', {$this->db->quote($val)}))";
                } else if ($ops[$i] == "AND NOT") {
                    $cond .= empty($cond) ? " INTERSECT ((" : "\nEXCEPT";
                    if (empty($field)) $cond .= $this->FTSQuery($val);
                    else $cond .= "\nSELECT edit_id FROM catalog
                        WHERE ({$field} to_tsvector('russian', value)
                            @@ to_tsquery('russian', {$this->db->quote($val)}))";
                }
            }
        }

        $cond .= empty($cond) ? ")" : ")))";
        $query = $search.$cond."\nSELECT c1.edit_id FROM search c1
  LEFT JOIN
        (SELECT edit_id, value FROM catalog WHERE field_id = {$sort}) c2
    using(edit_id) ORDER BY value";

        $query_count = $search.$cond."\nSELECT count(*) FROM search c1
  LEFT JOIN
        (SELECT edit_id, value FROM catalog WHERE field_id = {$sort}) c2
    using(edit_id)";

        return $this->SaveQuery($query, $query_count);
    }

    public function Search($id, $offset, $limit) {
        $res = $this->LoadQuery($id);
        $query = $res['query']. " LIMIT {$limit} OFFSET {$offset}";
        $query_count = $res['numrow'];

        $this->db->beginTransaction();

        $res = $this->db->SafeQuery($query);
        $num = $this->db->SafeQuery($query_count);

        $this->db->commit();

        $num = $num->fetch(DB::FETCH_NUM);
        return array('RESULT' => $res->fetchAll(DB::FETCH_NUM),
            'NUM' => $num[0]);
    }

    public function SimlpeSearch($type, $val) {

        $type = $type > -1 ? "edit_type = {$type}" : "";
        $query = "SELECT DISTINCT edit_id FROM ".$this->FTSQuery($val, $type, "catalog")
                ." m ORDER BY edit_id LIMIT 10";

        $res = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
        return $res;
    }

    private function FTSQuery($val, $cond = "", $from = "libstock") {
        $val = preg_replace('#\A\s+|\s+\z#', '', $val);
        $val = preg_replace(
            array("#[\|\(\)\:&\s]+#"),
            array(" "), $val);
        $val = explode(" ", $val);

        $cond = empty($cond) ? "" : $cond." AND";
        $subquery = "";
        foreach ($val as $v) {
            if (mb_strlen($v, "UTF-8") < 2) continue;
            $v = $this->db->quote($v);
            if (!empty($subquery)) $subquery .= "\nINTERSECT\n";
            $subquery .= " SELECT edit_id FROM {$from}
                WHERE {$cond} to_tsvector('russian', value)
                    @@ to_tsquery('russian', {$v})";
        }
        if (empty($subquery)) $subquery = "SELECT edit_id FROM {$from} WHERE false";
        $subquery = "(".$subquery.")";
        return $subquery;
    }

    private function SaveQuery($query, $numrow) {
        $this->db->SafeExec("INSERT INTO \"query\"(query, numrow)
            VALUES ({$this->db->quote($query)}, {$this->db->quote($numrow)})");
        return $this->db->lastInsertId("query_id");
    }

    private function LoadQuery($id) {
        $res = $this->db->SafeQuery("SELECT query, numrow
                FROM \"query\" WHERE query_id = {$id}")->fetch(DB::FETCH_ASSOC);
        return $res;
    }

    public function CountSearch() {

    }

    public function CatalogSearch($p, $offset) {
        $query = "SELECT catalog.edit_id FROM catalog
            WHERE field_id = {$p['field_id']} AND value = '{$p['value']}' LIMIT 10 OFFSET {$offset}";
        $res = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);

        $query = "SELECT count(*) FROM catalog
            WHERE field_id = {$p['field_id']} AND value = '{$p['value']}'";
        $num = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);

        return array('NUM' => $num[0], 'RESULT' => $res);
    }

    //////////////////////////////////////////////////////////////
    /////////////////////////ORDERS///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function OrderItems(array $items, $user) {
        $query = "INSERT INTO \"order\"(edit_id, user_id) VALUES";
        $count = count($items);
        for ($i = 0; $i < $count; ++$i) {
            $query .= "({$items[$i]}, {$user})".($i + 1 < $count ? "," : "");
        }
        $this->db->SafeExec($query);
    }

    public function CancelOrder($order_id) {
        $query = "UPDATE \"order\"
            SET stat_id = 4
            WHERE order_id = {$order_id}";
        $this->db->SafeExec($query);
    }

    public function IssueItem($p) {

        // изменение статусса издания
        $query = "UPDATE inventory SET stat_id = 2 WHERE item_id = {$p['item_id']}";
        $this->db->SafeExec($query);

        // изменение статусса заказа
        $query = "UPDATE \"order\" SET stat_id = 2 WHERE order_id = {$p['order_id']}";
        $this->db->SafeExec($query);

        // выдача
        $iss_date = $this->db->quote($p['iss_date']);
        $ret_date = $this->db->quote($p['ret_date']);
        $query = "INSERT INTO issue(order_id, item_id, iss_date, ret_date)
            VALUES({$p['order_id']}, {$p['item_id']}, {$iss_date}, {$ret_date})";
        $this->db->SafeExec($query);
    }

    public function ReturnItem($p) {
        $query = "SELECT order_id FROM issue JOIN \"order\" using(order_id)
            WHERE issue_id = {$p['issue_id']}";
        $order_id = $this->db->SafeQuery($query)->fetch();
        $order_id = $order_id[0];

        // изменение статусса издания
        $query = "UPDATE inventory SET stat_id = 1 WHERE item_id = {$p['item_id']}";
        $this->db->SafeExec($query);

        // изменение статусса заказа
        $query = "UPDATE \"order\" SET stat_id = 3 WHERE order_id = {$order_id}";
        $this->db->SafeExec($query);

        // возврат
        $ret_date = $this->db->quote($p['ret_date']);
        $query = "INSERT INTO \"return\"(issue_id, ret_date)
            VALUES({$p['issue_id']}, {$ret_date})";
        $this->db->SafeExec($query);

    }


    //////////////////////////////////////////////////////////////
    ////////////////////////DATAGET///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function GetFieldData($id) {
        $query = "SELECT field.name \"name\", field.type_id \"type_id\", field_id, field_type.name \"type_name\"
            FROM field, field_type
            WHERE field_id = '{$id}' AND field_type.type_id = field.type_id";
        return $this->db->SafeQuery($query)->fetch(DB::FETCH_ASSOC);
    }

    public function GetFieldsData() {
        $query = "SELECT field.name, sense,
                field.type_id, field_id, field_type.name \"type_name\"
            FROM field, field_type
            WHERE field_type.type_id = field.type_id
            ORDER BY field.name";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);
    }

    public function GetEditTypeFields($type_id) {
        $query = "SELECT field_id FROM type_field_rel
            WHERE type_field_rel.type_id = '{$type_id}'";
        $fields = array();
        $res = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
        foreach ($res as $i) {
            $fields[] = $i[0];
        }
        return $fields;
    }

    public function GetNumDictRecs($field_id, $cond = "") {
        $cond = empty($cond) ? "" : "AND ({$cond})";
        return $this->db->TableNumRows("dictionary", "field_id = '{$field_id}' {$cond}");
    }

    public function GetDictRecs($field_id, $cond, $start, $len) {
        $query = "SELECT value FROM dictionary
            WHERE field_id = '$field_id' AND ($cond) ORDER BY value LIMIT {$len} OFFSET {$start}";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
    }

    public function GetFirstEditType() {
        $type_id = $this->db->Table("edit_type")->fetch(DB::FETCH_NUM);
        return $type_id[0];
    }

    public function GetEditionTypes() {
        $query = "SELECT type_id, name FROM edit_type ORDER BY name";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);
    }

    public function GetItemStats() {
        $query = "SELECT stat_id, name, sense FROM item_status ORDER BY name";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);
    }

    public function GetCatalogDictRecs($field_id, $cond, $start, $len) {
        $query = "SELECT DISTINCT value FROM dictionary
            WHERE field_id = '$field_id' AND ($cond) ORDER BY value LIMIT {$len} OFFSET {$start}";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
    }

    public function GetCatalogNumDictRecs($field_id, $cond = "true") {
        $query = "SELECT DISTINCT count(*) FROM dictionary
            WHERE field_id = '$field_id' AND ($cond)";
        $num = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
        return $num[0];
    }


    // описание изданий
    public function GetEditBrief($edit_id, $temp = null) {
        $query = "SELECT field.field_id, value, field.name, dictionary.rec_id
            FROM dictionary, dict_rel, field, field_type
            WHERE edit_id = '{$edit_id}'
                AND dictionary.rec_id = dict_rel.rec_id
                AND field.field_id = dictionary.field_id
                AND field.type_id = field_type.type_id
                AND field_type.sense = 'STR'";
        $recs = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);

        $query = "SELECT name FROM edit_type, edition
            WHERE edit_id = '{$edit_id}' AND edit_type.type_id = edition.type_id";
        $type = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);

        $brief = new BriefList();
        $brief->AddRow('EditType', new Html\Text('Тип издания'), new Html\Text($type[0]));
        $brief->AddRow('EditId', new Html\Text('Номер издания'), new Html\Text($edit_id));

        foreach ($recs as $rec) {
            $i = $rec['field_id'];

            if (!$brief->Contains($i)) {
                $brief->AddRow($i, new Html\Text($rec['name']));
            } else {
                $brief->InsertValue($i, new Html\Text(", "));
            }
           $brief->InsertValue($i, new Html\Text($rec['value']));
        }

        return $brief;
    }

    public function GetEditInventoryBrief($edit_id) {

        $brief = $this->GetEditBrief($edit_id);

        // статус доступности
        $avail = $this->GetCountItems($edit_id)." шт.";
        $brief->AddRow('FreeCount', new Html\Text("В наличие"), new Html\Text($avail), true);

        return $brief;
    }

    public function GetEditCatalogBrief($edit_id) {

        $brief = $this->GetEditBrief($edit_id);

        // статус доступности
        $avail = $this->GetItemAvail($edit_id)." шт.";
        $brief->AddRow('FreeCount', new Html\Text("Доступно"), new Html\Text($avail), true);

        return $brief;
    }


    public function GetItemBrief($edit_id, $item_id) {

        $brief = $this->GetEditBrief($edit_id);

        $brief->InsertAfterRow('EditId', 'ItemId', new Html\Text('Номер экземпляра'),
                new Html\Text($item_id));
        return $brief;
    }

    public function GetEditDetailBrief($edit_id) {
        $query = "SELECT field.field_id, value, field.name,
                dict_data.path, sense
            FROM dictionary JOIN dict_rel using(rec_id)
                JOIN field using(field_id)
                JOIN field_type using(type_id)
                JOIN dict_data using(rec_id)
            WHERE edit_id = '{$edit_id}'";

        $recs = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);

        $brief = $this->GetEditBrief($edit_id);

        foreach ($recs as $rec) {
            $i = $rec['field_id'];

            if (!$brief->Contains($i)) {
                $brief->AddRow($i, new Html\Text($rec['name']));
            } else {
                $brief->InsertValue($i, new Html\Text(", "));
            }

            $val = $rec['sense'] == 'IMG' ? 'Смотреть' : 'Скачать';
            $a = new Html\A(array(
                'href' => $rec['path'],
                'target' => '_blank'
            ));
            $a->Add(new Html\Text($val));

            $brief->InsertValue($i, $a);
        }

        // статус доступности
        $avail = $this->GetItemAvail($edit_id)." шт.";
        $brief->AddRow('FreeCount', new Html\Text("Доступно"), new Html\Text($avail), true);

        return $brief;
    }



    // проверка доступности
    public function GetItemAvail($edit_id) {
        $query = "SELECT count(*) FROM inventory
            WHERE edit_id = {$edit_id} AND stat_id = 1";
        $avail = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
        return $avail[0];
    }

    public function GetCountItems($edit_id) {
        $query = "SELECT count(*) FROM inventory
            WHERE edit_id = {$edit_id}";
        $avail = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
        return $avail[0];
    }

    public function GetAvailableItem($edit_id) {
        $query = "SELECT item_id FROM inventory
            WHERE edit_id = {$edit_id} AND stat_id = 1 LIMIT 1";
        $item = $this->db->SafeQuery($query);

        if ($item->rowCount() > 0) {
            $item = $item->fetch(DB::FETCH_NUM);
            return $item[0];
        } else {
            return false;
        }

    }


    public function GetCatalogFields() {
        $query = "SELECT name, field.field_id
            FROM catalog_field JOIN field using(field_id)
            ORDER BY field.name";
        $fielsd = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);
        return $fielsd;
    }

    public function GetNoneCatalogFields() {
        $query = "SELECT field.name, field.field_id
            FROM field JOIN field_type using(type_id) LEFT JOIN catalog_field using(field_id)
            WHERE sense = 'STR' AND catalog_field.field_id IS NULL
            ORDER BY field.name";
        return $this->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);
    }

    public function SetCatalofFields(array $fields) {
        $this->db->beginTransaction();
        $query = "DELETE FROM catalog_field";
        $this->db->SafeExec($query);

        if (count($fields) > 0) {
            $query = "INSERT INTO catalog_field(field_id) VALUES";
            for ($i = 0; $i < count($fields); ++$i) {
                $query .= "\n({$fields[$i]})";
                if ($i < count($fields) - 1) $query.= ",";
            }
            $this->db->SafeExec($query);
        }
        $this->db->commit();
    }





//    public function GetDateIssue($order_id) {
//        $query = "SELECT iss_date FROM issue WHERE order_id = {$order_id}";
//        $date = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
//        return $date[0];
//    }
//
//    public function GetDateReturn($issue_id) {
//        $query = "SELECT ret_date FROM \"return\" WHERE issue_id = {$issue_id}";
//        $date = $this->db->SafeQuery($query)->fetchAll(DB::FETCH_NUM);
//        return $date[0];
//    }
//
//    public function FindOrders($p) {
//        $query = "SELECT count(*) FROM \"order\"
//            WHERE user_id = {$p['user_id']} AND edit_id = {$p['edit_id']} AND stat_id in (1, 2)";
//        $count = $this->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
//        return $count[0];
//    }
}
